<template>
  <!-- 导航 -->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>项目管理</el-breadcrumb-item>
        <el-breadcrumb-item>所有项目列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>
  <!-- 搜索栏-->
  <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
    <el-col :span="24">
      <el-form :model="projectQuery" inline>
        <el-form-item label="项目名称">
          <el-input v-model="projectQuery.projectName"/>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTimes"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="loadProjects" type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
    <el-col :span="24">
      <el-button-group>
        <el-button type="primary">编辑</el-button>
        <el-button type="primary" @click="handlePigeonhole">恢复</el-button>


      </el-button-group>


      <el-dialog v-model="dialogNotPigeonholeVisible"
                 title="无法恢复的项目"
      >
        <p v-for="id in nonPigeonholeHandleProjectIds" :key="id">项目{{id}}无法恢复</p>
        <span slot="footer" class="dialog-footer">
              <el-button @click="dialogNotPigeonholeVisible = false">关闭</el-button>
            </span>
      </el-dialog>

    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-table :data="projects" border stripe ref="projectTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="projectId" label="#">
          <template #default="scope">
            <el-link type="success" @click="handleProjectClick(scope.row.projectId)">
              {{ scope.row.projectId }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="projectName" label="项目名称"/>
        <el-table-column prop="user.username" label="管理者"/>
        <el-table-column label="任务数量">
          <template #default>
            100
          </template>
        </el-table-column>
        <el-table-column prop="projectStatus" label="项目状态">
          <template #default="scope">
            <el-tag type="danger" v-if="scope.row.projectStatus == 99">删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间"/>
        <el-table-column prop="endTime" label="结束时间"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="330">
          <template #default="scope">
            <el-button-group>
              <template v-if="scope.row.userId == currUserId">

                <el-button size="small" type="primary" @click="editProject(scope.row.projectId)">编辑</el-button>

                <el-popconfirm
                    title="真的确定恢复吗?"
                    @confirm="() => pigeonholeProjectConfirm(scope.row.projectId)"
                    @cancel="pigeonholeProjectCancel"
                >
                  <template #reference>
                    <el-button size="small" type="info" >恢复</el-button>
                  </template>
                </el-popconfirm>


              </template>
              <el-button size="small" type="primary">任务</el-button>
              <el-button size="small" type="primary">日历</el-button>
            </el-button-group>

          </template>
        </el-table-column>
      </el-table>


      <!--          //项目编辑弹窗-->
      <el-dialog v-model="dialogEditVisible" title="项目编辑">
        <el-form :model="projectDetail" ref="formRef" label-width="120px">
          <el-form-item label="项目编号">
            <el-input v-model="projectDetail.projectId" disabled></el-input>
          </el-form-item>

          <el-form-item label="名称">
            <el-input v-model="projectDetail.projectName"></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="projectDetail.projectStatus" placeholder="请选择状态">
              <el-option label="草稿" value="1"></el-option>
              <el-option label="发布" value="2"></el-option>
              <el-option label="归档" value="3"></el-option>
              <el-option label="暂停" value="4"></el-option>
              <el-option label="意外" value="5"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="管理者">
            <el-input v-model="projectDetail.userId" disabled></el-input>
            <!--                管理者后面要将userId传到后端送一个名字过来 //TODO
            -->
          </el-form-item>

          <el-form-item label="发布时间">
            <el-input v-model="projectDetail.createTime" disabled></el-input>
          </el-form-item>

          <el-form-item label="开始时间">
            <el-date-picker
                v-model="projectDetail.startTime"
                type="date"
                placeholder="选择开始时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="结束时间">
            <el-date-picker
                v-model="projectDetail.endTime"
                type="date"
                placeholder="选择结束时间">
            </el-date-picker>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
              <el-button @click="dialogEditVisible = false">关闭</el-button>
               <el-button type="primary" @click="saveProject(projectDetail)">保存</el-button>
            </span>
      </el-dialog>

      <!--  查看项目详情-->
      <el-dialog v-model="dialogProjectVisible" title="项目详情">
        <div v-if="projectDetail">
          <p>项目名称：{{projectDetail.projectName}}</p>
          <p>项目描述：{{projectDetail.projectDesc}}</p>
          <p>项目的任务列表:  还没做
            <!--                任务列表待完成 //TODO-->
          </p>
        </div>

        <p>ok</p>
        <span slot="footer" class="dialog-footer">
              <el-button @click="dialogProjectVisible = false">关闭</el-button>
            </span>
      </el-dialog>
    </el-col>
  </el-row>
  <el-row style="margin: 0px 10px;padding: 0px 15px">
    <el-col :span="24">
      <el-pagination @change="changePage" background layout="prev, pager, next" :total="total"/>
    </el-col>
  </el-row>

</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import projectRequest from "@/api/project.js";
import {useRouter} from "vue-router";
import project from "@/api/project.js";
import callbackify from "axios/unsafe/helpers/callbackify.js";
import axios from "axios";
// 封装搜索数据的对象
let projectQuery = ref({projectStatus: 99})
// 封装两个时间范围
let startTimes = ref([]);
let endTimes = ref([]);
// 查询的项目列表
let projects = ref([]);
// 总条数，默认0
let total = ref(0);
// 当前页码，默认1
let curPage = ref(1);
// 当前登录用户的编号
let currUserId = ref();
let router = useRouter();
const dialogProjectVisible = ref(false); // 控制项目详情的显示
const selectedProjectId = ref(null); // 选中的项目 ID
const projectDetail = ref(null);
const dialogEditVisible = ref(false);
const saveProjectOne = ref(null) ;//临时保存编辑的项目用
const selectedProjects = ref([]);
const nonPigeonholeHandleProjectIds = ref([]);//无法恢复的项目
const dialogNotPigeonholeVisible = ref(false);//默认设置无法恢复的弹窗为false
const nonDelHandleProjectIds = ref([]);
const dialogNotDelVisible = ref(false);
//批量选择
const handleSelectionChange = (selectedRows) =>{
  selectedProjects.value = selectedRows;//更新选中的项目

}

//批量恢复实现
const handlePigeonhole = async () =>{
  const nonPigeonholeHandleProjects = selectedProjects.value.filter(project => project.user.userId != currUserId.value);
  nonPigeonholeHandleProjectIds.value = nonPigeonholeHandleProjects.map(project => project.projectId);
  if (nonPigeonholeHandleProjects.length > 0){
    dialogNotPigeonholeVisible.value = true;
  }else {
    const selectedProjectIds = selectedProjects.value.map(project => project.projectId);
    let url = "http://localhost:8080/project/batch/recover?a=1";
    selectedProjectIds.forEach(id =>{
      url += "&projectIds=" +id;
    })
    const response = await axios.post(url)
  }
  loadProjects();
}


//列恢复相关
const pigeonholeProjectConfirm =async (projectId) =>{
  if (!projectId){
    console.error('项目id无效');
    return;
  }
  selectedProjectId.value = projectId;
// 通过当前id请求去修改后端对应project的status
  try{
    const response = await axios.put(`http://localhost:8080/project/recover/${projectId}`)
    console.log("ok")
    loadProjects();
  }catch (error){
    console.error(error);
  }
}

//单行编辑按钮
const editProject = async (projectId) =>{
  selectedProjectId.value = projectId;
  try {
    const response = await axios.get(`http://localhost:8080/project/search/${projectId}`)
    projectDetail.value = response.data;
    dialogEditVisible.value = true;
  }catch (error){
    console.error(error);
  }
}
//单行编辑内部的保存按钮
const saveProject = async (projectDetail) =>{
  saveProjectOne.value = projectDetail;
  selectedProjectId.value = projectDetail.projectId;
  try {
    const response = await axios.put(`http://localhost:8080/project/save/${projectDetail.projectId}`,projectDetail)
    console.log("ok")
  }catch (error){
    console.error(error);
  }
}

//显示具体项目信息
const handleProjectClick = async (projectId) => {
  selectedProjectId.value = projectId; // 设置选中的项目 ID
  try {
    const response = await axios.get(`http://localhost:8080/project/search/${projectId}`)//从后端请求数据
    console.log(response.data)
    projectDetail.value = response.data;//将请求的数据传入到ProjectDetail中
    dialogProjectVisible.value = true; // 显示对话框
  }catch (error){
    console.error(error);
  }
};


// 富文本编辑器相关的属性
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML ，如果我们修改了内容，这里会跟着变化
const valueHtml = ref('<p>hello</p>')
// 工具栏配置
const toolbarConfig = {
}
const projectId = ref(project.projectId);
// 编辑器配置
const editorConfig = { placeholder: '请输入内容...' }







// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}



/**
 * 新增项目的提交按钮事件
 */
function addProjectSubmit(){
  console.log(valueHtml.value)
}
/**
 * 加载项目列表
 */
function loadProjects() {
  //处理查询条件，处理时间范围
  if (startTimes.value[0]) {
    projectQuery.value.startTimeBegin = startTimes.value[0];
  }
  if (startTimes.value[1]) {
    projectQuery.value.startTimeEnd = startTimes.value[1];
  }
  if (endTimes.value[0]) {
    projectQuery.value.endTimeBegin = endTimes.value[0];
  }
  if (endTimes.value[1]) {
    projectQuery.value.endTimeBegin = startTimes.value[1];
  }
  // 调用API来查询项目列表
  projectRequest.loadDeleteProjects(projectQuery.value, curPage.value, 10, res => {

    // 这里的res就是后端返回的结果
    // 总条数赋值
    total.value = res.data.total;
    // 将查询的列表赋值给projects
    projects.value = res.data.list;
  })
}

// 分页事件
function changePage(value) {
  curPage.value = value;
  loadProjects();
}

onMounted(() => {
  loadProjects();
  // 从localStorage中获取用户编号
  currUserId.value = localStorage.getItem("userId");
  if (currUserId.value == undefined || currUserId.value == '') {
    // 进入登录页面
    router.push("/");
  }
  currUserId.value = localStorage.getItem("userId");
})
</script>

<style scoped>

</style>